package hoang.android.app.ui.missatool;

import hoang.android.app.R;
import hoang.android.app.info.WebServiceConfig;
import hoang.android.app.item.AddTripLayout;
import hoang.android.app.json.ParameterFactory;
import hoang.android.app.json.ParserJson;
import hoang.android.app.model.Account;
import hoang.android.app.model.TripInfo;
import hoang.android.app.network.AsyncHttpGet;
import hoang.android.app.network.AsyncHttpPost;
import hoang.android.app.network.AsyncHttpResponseProcess;
import hoang.android.app.ui.BaseActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class TripInfoActivity extends BaseActivity {
	
//	public static final int ALL_ROADS = 0;
	public static final int ROAD_73 = 1;
	public static final int ROAD_241 = 2;
	
	private ArrayList<TripInfo> arrayInfors;

	Button img_add_trip;

	EditText etDate;
	ImageView imgDialogDate;

	Spinner spTollRoad, spEntryPoint, spExitPoint;
	
	private ArrayAdapter<String> adapterTollRoad, adapter;
	private ArrayList<String> arrayPoint1, arrayPoint2;
	
//	private ArrayList<String> loc_id1, loc_id2, loc_id;
	
	private Account account;
	
	private String start_date, from_loc, to_loc;
	
	private TextView totalPrevious, totalRate;
	
	private TableLayout tl_listtrip;
	
	private Button bt_next;
	
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_trip_info);

		int SDK_INT = android.os.Build.VERSION.SDK_INT;
		if (SDK_INT > 8) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
		loadUI();
		
		//setHeader(true,	baseActivity.getResources().getString(R.string.trip_info));
		
		//lay ket qua parser
		arrayInfors = new ArrayList<TripInfo>();
		loadLocationList();
		
		setupListenUI();
	}
	
	/**
	 * khi vao giao dien nay se load danh sach cac tuyen duong va cac doan duong cua tuyen do
	 */
	
	private void loadLocationList(){
		
		//buoc1: tao giao thuc truyen len
		List<NameValuePair> params = null;
		params = ParameterFactory.createParamsLocList(account.get_tokenID(), WebServiceConfig.ACTION_LOC_LIST, "0", "0");
		
		//buoc2: su dung cac giao thuc ma server dinh nghia: giao thuc Get(Post)
		AsyncHttpGet httpGet = new AsyncHttpGet(
				baseActivity, 
				new AsyncHttpResponseProcess(this, true){
					@Override
					public void processIfResponseSuccess(JSONObject json) {
						//buoc3: xu ly ket qua tra ve
						super.processIfResponseSuccess(json);
						processGetLocListSuccess(json);
					}
					
				},
				params);
		
		//buoc4: thuc hien gui request
		httpGet.execute(WebServiceConfig.API_GET_LOCATION_LIST);
	}
	
	private void processGetLocListSuccess(JSONObject json){
		
		ArrayList<TripInfo> infos = new ArrayList<TripInfo>();
		
		try {
			
			infos = ParserJson.parserLocationList(json);
			
			for(TripInfo tripinfor : infos){	
				arrayInfors.add(tripinfor);
				
				if(tripinfor.getToll_road().equals("1")){
					//ten cua doan duong thuoc tuyen 241/161/133
					arrayPoint1.add(tripinfor.getLoc_name());
//					loc_id1.add(tripinfor.getLoc_id());
				}else{
					//ten cua doan duong thuoc tuyen 73
					arrayPoint2.add(tripinfor.getLoc_name());
//					loc_id2.add(tripinfor.getLoc_id());
				}
			}
			
			//sau do goi phuong thuc de update adapter
			//adapter.dataSetChange()
			
			initWitget();
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setupAdapter(int i){
		//ArrayList<String> array = new ArrayList<String>();
//		arrayPoint.clear();
//		adapter.clear();
//		loc_id.clear();
		switch (i) {
		/*case ALL_ROADS:
			arrayPoint.clear();
			arrayPoint.addAll(arrayPoint2);
			arrayPoint.addAll(arrayPoint1);
			
			loc_id.addAll(loc_id2);
			loc_id.addAll(loc_id1);
			break;*/
		case ROAD_73:
//			arrayPoint.addAll(arrayPoint2);
//			loc_id.addAll(loc_id2);
			adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint2);
			break;
		case ROAD_241:
			adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint1);
//			arrayPoint.addAll(arrayPoint1);
//			loc_id.addAll(loc_id1);
			break;

		default:
			break;
		}
		
//		ArrayAdapter<String> adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint);
		spEntryPoint.setAdapter(adapter);
		spExitPoint.setAdapter(adapter);
	}

	public void setupListenUI() {
		img_add_trip.setOnClickListener(this);
		imgDialogDate.setOnClickListener(this);
		bt_next.setOnClickListener(this);
		
		spEntryPoint.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

//				from_loc = arrayPoint1.get(arg2);
				from_loc = (String) arg0.getItemAtPosition(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

//				from_loc = arrayPoint1.get(0);
				from_loc = (String) arg0.getItemAtPosition(0);
			}
		});
		
		spExitPoint.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

//				to_loc = arrayPoint2.get(arg2);
				to_loc = (String) arg0.getItemAtPosition(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

//				to_loc = arrayPoint2.get(0);
				to_loc = (String) arg0.getItemAtPosition(0);
			}
		});
		
		spTollRoad.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				if(arg2==0){
//					setupAdapter(ROAD_73);
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint2);
					spEntryPoint.setAdapter(adapter);
					spExitPoint.setAdapter(adapter);
				}else{
//					setupAdapter(ROAD_241);
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint1);
					spEntryPoint.setAdapter(adapter);
					spExitPoint.setAdapter(adapter);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				setupAdapter(ROAD_73);
			}
		});
	}

	@Override
	protected void loadUI() {
		//super.loadUI();
		
		totalPrevious = (TextView)findViewById(R.id.totalPrevious);
		totalRate = (TextView)findViewById(R.id.totalRate);

		img_add_trip = (Button) findViewById(R.id.img_add_trip);

		etDate = (EditText) findViewById(R.id.et_date);
		spTollRoad = (Spinner) findViewById(R.id.sp_road);
		spEntryPoint = (Spinner) findViewById(R.id.sp_entry_point);
		spExitPoint = (Spinner) findViewById(R.id.sp_exit_point);
		imgDialogDate = (ImageView)findViewById(R.id.img_date);

		account = application.getAccount();
		
		totalPrevious = (TextView)findViewById(R.id.totalPrevious);
		totalRate = (TextView)findViewById(R.id.totalRate);
		tl_listtrip = (TableLayout)findViewById(R.id.listTrip);
		
		bt_next = (Button)findViewById(R.id.bt_next);
		
		arrayPoint1 = new ArrayList<String>();
		arrayPoint2 = new ArrayList<String>();
		
	}
	
	public void initWitget(){
		
		adapterTollRoad = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.toll_road));
		spTollRoad.setAdapter(adapterTollRoad);
		
//		setupAdapter(ROAD_73);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(baseActivity, android.R.layout.simple_spinner_item, arrayPoint2);
		spEntryPoint.setAdapter(adapter);
		spExitPoint.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);

		switch (v.getId()) {
		case R.id.img_add_trip:
			if(checkValidate()){
				addTrip();
			}else{
				showPositiveCustomDialog(baseActivity, "Error", "Entrypoint and Extipoinyt same", R.drawable.button_ok);
			}
				
			break;
		case R.id.img_date:
			showDateTimePicker();
			break;
		case R.id.bt_next:
			startActivity(new Intent(baseActivity, PaymentActivity.class));
			break;
		default:
			break;
		}
	}
	
	public void addTrip(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		
		params = ParameterFactory.createParamsAddTrip(account.get_tokenID(), start_date, getLocIdFromLocName(from_loc), getLocIdFromLocName(to_loc), WebServiceConfig.ACTION_ADD_TRIP);
		
		Log.d("TEST", "addtrip params: "+ params.toString());
		
		AsyncHttpPost httpPost = new AsyncHttpPost(
				baseActivity, 
				new AsyncHttpResponseProcess(this, true){
					@Override
					public void processIfResponseSuccess(JSONObject json) {
						super.processIfResponseSuccess(json);
						
						getListTrip();
					}
				}, 
				params);
		
		httpPost.execute(WebServiceConfig.API_ADD_TRIP);
	}
	
	/**
	 * phuong thuc show datedialog
	 * chon ngay set cho edittext date
	 */
	public void showDateTimePicker() {
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		
		DatePickerDialog datepicker = new DatePickerDialog(baseActivity, new OnDateSetListener() {
			
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				
				etDate.setText(getStringFormat(dayOfMonth, monthOfYear, year));
				start_date = getStringFormat1(dayOfMonth, monthOfYear, year);
				
			}
		}, year, month, day);
		datepicker.show();
	}
	
	public String getStringFormat(int day, int month, int year){
		String s1 = String.valueOf(day);
		String s2 = String.valueOf(month+1);
		String s3 = String.valueOf(year);
		
		if(day<10){
			s1 = "0"+s1;
		}
		
		if(month+1<10){
			s2 = "0"+s2;
		}
		
		return s2+"/"+s1+"/"+s3;
	}
	
	public String getStringFormat1(int day, int month, int year){
		String s1 = String.valueOf(day);
		String s2 = String.valueOf(month+1);
		String s3 = String.valueOf(year);
		
		if(day<10){
			s1 = "0"+s1;
		}
		
		if(month+1<10){
			s2 = "0"+s2;
		}
		
		return s3+"-"+s2+"-"+s1;
	}
	
	// xay dung phuong thuc kiem tra 2 diem di phai khac nhau
	private boolean checkValidate() {
		return !from_loc.equals(to_loc);
	}
	
	//xay dung phuong thuc de lay danh doạn đương vừa mới nhập thanh công
	private void getListTrip(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params = ParameterFactory.createParamsGetListTrip(account.get_tokenID(), WebServiceConfig.ACTION_TRIP_LIST);
		
		Log.d("TEST", "listtrip params "+params.toString());
		
		AsyncHttpPost httpPost = new AsyncHttpPost(
				baseActivity, 
				new AsyncHttpResponseProcess(this, true){
					@Override
					public void processIfResponseSuccess(JSONObject json) {
						super.processIfResponseSuccess(json);
						
						processGetListTripSuccess(json);
					}
				}, 
				params);
		
		httpPost.execute(WebServiceConfig.API_GET_LIST_TRIP);
	}
	
	private void processGetListTripSuccess(JSONObject json){
		try {
			
			String amount_due = json.getString(WebServiceConfig.PARAM_AMOUNT_DUE);
			String previous_amount_due = json.getString(WebServiceConfig.PARAM_PREVIOUS_AMOUNT_DUE);
			
			totalPrevious.setText(previous_amount_due);
			totalRate.setText(amount_due);
			
			JSONArray infos = json.getJSONArray(WebServiceConfig.PARAM_INFO);
			
			tl_listtrip.removeAllViews();
			
			for(int i=0; i<infos.length(); i++){
				int trip_num = infos.getJSONObject(i).getInt(WebServiceConfig.PARAM_TRIP_NUM);
				int from_loc_id = infos.getJSONObject(i).getInt(WebServiceConfig.PARAM_FROM_LOC_ID);
				int to_loc_id = infos.getJSONObject(i).getInt(WebServiceConfig.PARAM_TO_LOC_ID);
				String trip_date = infos.getJSONObject(i).getString(WebServiceConfig.PARAM_TRIP_DATE);
				String trip_amount = infos.getJSONObject(i).getString(WebServiceConfig.PARAM_TRIP_AMOUNT);
				
				AddTripLayout item = new AddTripLayout(baseActivity, trip_date, getLocNameFromLocId(from_loc_id), getLocNameFromLocId(to_loc_id), trip_amount, trip_num);
				tl_listtrip.addView(item);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void deleteTrip(View view){
		
		int trip_num = (Integer) view.getTag();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params = ParameterFactory.createParamsDeleteTrip(account.get_tokenID(), String.valueOf(trip_num), WebServiceConfig.ACTION_DEL_LIST);
		
		Log.d("TEST", "delete trip "+params.toString());
		
		AsyncHttpPost httpPost = new AsyncHttpPost(
				baseActivity, 
				new AsyncHttpResponseProcess(this, true){
					@Override
					public void processIfResponseSuccess(JSONObject json) {
						super.processIfResponseSuccess(json);
						
						getListTrip();
					}
				}, 
				params);
		
		httpPost.execute(WebServiceConfig.API_GET_DEL_TRIP);
	}
	
	/**
	 * phuong thuc lay loccation name tu loction id
	 * 
	 * @param loc_id
	 * @return
	 */
	public String getLocNameFromLocId(int loc_id){
		
		for(TripInfo info:arrayInfors){
			if(Integer.valueOf(info.getLoc_id())==loc_id){
				return info.getLoc_name();
			}
		}
		
		return null;
	}
	
	public String getLocIdFromLocName(String loc_name){
		
		for(TripInfo info:arrayInfors){
			if(info.getLoc_name().equals(loc_name)){
				return info.getLoc_id();
			}
		}
		
		return null;
	}
}
